# -*- coding: utf-8 -*-
"""
@File    :   user.py
@Time    :   2024/04/12 11:30:56
@Author  :   Ennis.Zhou 
@Desc    :   None
"""
import uuid

from datetime import datetime

from werkzeug.security import generate_password_hash, check_password_hash

from apps import db


class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""

    create_time = db.Column(db.DateTime, default=datetime.now)  # 记录的创建时间
    update_time = db.Column(
        db.DateTime, default=datetime.now, onupdate=datetime.now
    )  # 记录的更新时间


class User(BaseModel, db.Model):
    """用户"""

    __tablename__ = "i_user"
    # id = db.Column(db.String(50), primary_key=True, autoincrement=True, comment="用户ID")
    id = db.Column(db.String(50), primary_key=True, comment="用户ID")
    nickname = db.Column(db.String(30), comment="用户昵称")
    username = db.Column(db.String(30), comment="登录账号")
    sex = db.Column(db.INTEGER, default=1, comment="用户性别（1男 2女 3未知）")
    phone = db.Column(db.String(30), comment="手机号码")
    avatar = db.Column(db.String(100), comment="头像路径")
    password_hash = db.Column(db.String(255), comment="密码")
    account_status = db.Column(db.INTEGER, default=1, comment="帐号状态（1正常 2禁用")

    def __init__(self, kwargs):
        # self.id = user_id
        self.id = str(uuid.uuid4())
        self.username = kwargs['username']
        self.nickname = kwargs['nickname']
        self.phone = kwargs['phone']
        self.avatar = kwargs['avatar']
        self.sex = kwargs['sex']
        self.password = kwargs['password']
        self.account_status = kwargs['account_status']

    # 加上property装饰器后，会把函数变为属性，属性名即为函数名
    @property
    def password(self):
        """读取属性的函数行为"""
        # print(User.password)  # 读取属性时被调用
        # 函数的返回值会作为属性值
        # return "xxxx"
        # raise AttributeError("这个属性只能设置，不能读取")
        return self.password_hash

    # 使用这个装饰器, 对应设置属性操作
    @password.setter
    def password(self, value):
        """
        设置属性  user.passord = "xxxxx"
        :param value: 设置属性时的数据 value就是"xxxxx", 原始的明文密码
        :return:
        """
        self.password_hash = generate_password_hash(value)

    def check_user_pwd(self, pwd):
        return check_password_hash(self.password, pwd)

    def to_user_dict(self):
        """将用户基本信息转换为字典数据"""
        user_dict = {
            "id": self.id,
            "nickname": self.nickname,
            "username": self.username,
            "avatar": self.avatar,
            "phone": self.phone,
            "sex": self.sex,
            "account_status": self.account_status
        }
        return user_dict

    def save_data(self):
        """保存数据"""
        db.session.add(self)
        db.session.commit()

    def update_data(self):
        """保存数据"""
        db.session.commit()

    def delete_data(self):
        db.session.delete(self)
        db.session.commit()

    def verification(self):
        user_phone = User.query.filter_by(phone=self.phone).first()
        user_name = User.query.filter_by(username=self.username).first()
        if user_phone or user_name:
            return True
        return False

    def __repr__(self):
        return f"<Users(id='{self.id}', username='{self.username}'...)>"
